package com.example.crm.controller;

import com.example.crm.entity.Right;
import com.example.crm.entity.User;
import com.example.crm.service.IRightService;
import com.example.crm.service.IUserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
public class LoginController {
    @Resource
    private IUserService userService;
    @Resource
    private IRightService rightService;
    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }
    @RequestMapping("/dologin")
    public String dologin(@RequestParam("usrName") String usrName,@RequestParam("usrPassword") String usrPassword, HttpSession session, Model model){
//        User user=userService.login(usrName,usrPassword);
//        if(user != null){
//            session.setAttribute("user",user);
//            return "redirect:/tomain";
//        }else {
//            session.setAttribute("msg","用户名或密码错误");
//            return "login";
//        }
        try{
            UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            User user = (User) subject.getPrincipal();
            List<Right> list = rightService.list();
            session.setAttribute("user",user);
            session.setAttribute("rights",list);
            return "redirect:/tomain";
        }catch (LockedAccountException e){
           model.addAttribute("msg","用户被禁用登录失败");
            return "login";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("msg","用户或密码错误，登陆失败");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("msg","认证异常，登陆失败");
            return "login";
        }
    }
    @RequestMapping("/tomain")
    public String list(){
        return "main";
    }

    @RequestMapping(value = "/403")
    public String unauthorized() {
        return "403";
    }
}
